package com.ponhu.ea2.goodsCenter.provider.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ponhu.ea2.entity.Goods;
import com.ponhu.ea2.entity.GoodsInventoryMd;
import com.ponhu.ea2.entity.Inventory;
import com.ponhu.ea2.entity.PhGoodsSyncLogs;
import com.ponhu.ea2.enums.SyncTaskTypeEnum;
import com.ponhu.ea2.enums.YesOrNoEnum;
import com.ponhu.ea2.goodsCenter.provider.mapper.GoodsMapper;
import com.ponhu.ea2.goodsCenter.provider.mapper.InventoryMapper;
import com.ponhu.ea2.goodsCenter.provider.utils.RandomUtil;
import com.ponhu.ea2.vo.GoodsDataAttributeSyncVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author zhaokai
 */
@Slf4j
@Service
public class GoodsDataSyncService {

    /**
     * 标品渠道固定税率
     */
    private final BigDecimal PURCHASE_TAX = new BigDecimal(0.13);

    /**
     * 其他渠道固定税率
     */
    private final BigDecimal OTHER_PURCHASE_TAX = new BigDecimal(0.02);

    /**
     * List分割条数
     */
    private final Integer LIST_LIMIT = 20000;

    /**
     * 货品类型：标品数据
     */
    private final Integer FIRST_CHANNEL = 5;

    public static final int CONSTANTINTONE = 1;

    public static final String CONSTANTINTTWO = "2";

    public static final int CONSTANTINTZERO = 0;

    /**
     * 更新人
     */
    private final String UPDATE_BY_NAME = "胖总管操作人员";


    /**
     * 货品单位
     */
    private final String INVENTORY_UNIT = "件";


    @Resource
    InventoryService inventoryService;
    @Resource
    GoodsInventoryMdService goodsInventoryMdService;
    @Resource
    GoodsService goodsService;
    @Resource
    PhGoodsSyncLogsService phGoodsSyncLogsService;
    @Resource
    GoodsMapper goodsMapper;
    @Resource
    InventoryMapper inventoryMapper;

    /**
     * 商品属性数据同步
     */
//    @Transactional(rollbackFor = Exception.class)
    public void goodsAttributeDataSync(List<GoodsDataAttributeSyncVo> goodsDataAttributeSyncVos) {
        try {
            // 按指定条数进行数据分割处理
            List<List<GoodsDataAttributeSyncVo>> parts = Lists.partition(goodsDataAttributeSyncVos, LIST_LIMIT);
            parts.stream().forEach(list -> {
                process(goodsDataAttributeSyncVos);
            });
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 遍历/保存数据
     *
     * @param goodsDataAttributeSyncVos
     */
    private void process(List<GoodsDataAttributeSyncVo> goodsDataAttributeSyncVos) {
        for (GoodsDataAttributeSyncVo dataAttributeSyncVo : goodsDataAttributeSyncVos) {
            // 通过库存编码查询是否已同步过信息
            boolean isExitInventoryData = checkIsExitInventoryData(dataAttributeSyncVo);
            if (isExitInventoryData) {
                updateGoodsDataAttributeData(dataAttributeSyncVo);
            } else {
                addGoodsDataAttributeData(dataAttributeSyncVo);
            }
        }
    }

    /**
     * 更新数据
     *
     * @param dataAttributeSyncVo
     */
    public void updateGoodsDataAttributeData(GoodsDataAttributeSyncVo dataAttributeSyncVo) {
        log.info("商品中心属性数据，更新数据，{}", dataAttributeSyncVo);
        Inventory inventory = new Inventory();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("inventory_code", dataAttributeSyncVo.getCode());
            inventory = inventoryService.getOne(wrapper);
            setInventoryData(inventory, dataAttributeSyncVo);
            // 更新库存信息
            boolean inventoryUpdate = inventoryService.updateById(inventory);
            if (inventoryUpdate) {
                log.info("商品中心属性数据，货品信息更新成功...");
            }
            // 通过中间表取商品数据
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("inventory_id", inventory.getId());
            GoodsInventoryMd goodsInventoryMd = goodsInventoryMdService.getOne(queryWrapper);
            // 如果中间表没有数据，说明在生成商品数据时出现了异常，没有保存成功，需要再重新进行商品数据创建
            if (null != goodsInventoryMd) {
                // 更新商品信息
                Goods goods = goodsService.getById(goodsInventoryMd.getGoodsId());
                setGoodsAttributeData(goods, dataAttributeSyncVo);
                boolean goodsUpdate = goodsService.updateById(goods);
                if (goodsUpdate) {
//                    saveGoodsSyncLog(inventory.getInventoryCode(), CONSTANTINTONE, "更新货品与商品属性参数:" + JSON.toJSON(dataAttributeSyncVo).toString());
                    log.info("商品中心属性数据，商品信息更新成功...");
                }
            } else {
                // 生成中间数据
                Goods newGoods = new Goods();
                setGoodsAttributeData(newGoods, dataAttributeSyncVo);
                boolean goodsSave = goodsService.save(newGoods);
                if (goodsSave) {
                    log.info("商品中心属性数据，新增商品信息成功...");
                    // 创建中间表信息
                    saveMdData(newGoods, inventory, dataAttributeSyncVo);
                }
            }
        } catch (Exception e) {
            log.error("商品中心属性数据，货品或商品信息更新异常{}", e.getMessage());
            saveGoodsSyncLog(inventory.getInventoryCode(), Integer.parseInt(CONSTANTINTTWO), "更新货品与商品属性，异常错误：" + e.getMessage() + "，异常参数:" + JSON.toJSON(dataAttributeSyncVo).toString(),SyncTaskTypeEnum.ATTRIBUTE.getCode());
            throw e;
        }
    }

    /**
     * 添加数据
     *
     * @param dataAttributeSyncVo
     */
    public void addGoodsDataAttributeData(GoodsDataAttributeSyncVo dataAttributeSyncVo) {
        log.info("商品中心属性数据，新增数据，{}", dataAttributeSyncVo);
        Inventory inventory = new Inventory();
        try {
            setInventoryData(inventory, dataAttributeSyncVo);
            // 创建货品信息
            boolean inventorySave = inventoryService.save(inventory);
            if (inventorySave) {
                log.info("商品中心属性数据，新增货品信息成功...");
                // 创建商品信息
                Goods goods = new Goods();
                setGoodsAttributeData(goods, dataAttributeSyncVo);
                boolean goodsSave = goodsService.save(goods);
                if (goodsSave) {
                    log.info("商品中心属性数据，新增商品信息成功...");
                    // 创建中间表信息
                    saveMdData(goods, inventory, dataAttributeSyncVo);
                }
            }
        } catch (Exception e) {
            log.error("商品中心属性数据，货品或商品信息新增异常：{}", e.getMessage());
            saveGoodsSyncLog(inventory.getInventoryCode(), Integer.parseInt(CONSTANTINTTWO), "新增货品与商品属性，异常错误：" + e.getMessage() + "，异常参数:" + JSON.toJSON(dataAttributeSyncVo).toString(),SyncTaskTypeEnum.ATTRIBUTE.getCode());
            throw e;
        }
    }

    public boolean checkIsExitInventoryData(GoodsDataAttributeSyncVo dataAttributeSyncVo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("inventory_code", dataAttributeSyncVo.getCode());
        Integer count = inventoryService.count(wrapper);
        return count > 0;
    }

    /**
     * 商品属性数据
     *
     * @param dataAttributeSyncVo
     */
    private Goods setGoodsAttributeData(Goods goods, GoodsDataAttributeSyncVo dataAttributeSyncVo) {
        if (null != goods && null != goods.getId()) {
            goods.setUpdatedTime(LocalDateTime.now());
            // 更新人姓名
            goods.setUpdatedByName(UPDATE_BY_NAME);
        } else {
            // 商品编码
            // 生成商品编码
            String goodsCode = RandomUtil.createGoodsCode();
            // 校验编码是否存在
            while (checkIsExistGoodsCode(goodsCode)) {
                goodsCode = RandomUtil.createGoodsCode();
            }
            goods.setGoodsCode(goodsCode);
            // 创建时间
            goods.setCreatedTime(LocalDateTime.now());
            //商品状态 初始值为1
            goods.setGoodsStatus(1);
            // 默认商品类型1
            goods.setType(1);
        }
        // 含税销售价
        if (StringUtils.isNotBlank(dataAttributeSyncVo.getBPrice()) && !StringUtils.equals(dataAttributeSyncVo.getBPrice(), "null")) {
            goods.setSaleTaxPrice(new BigDecimal(dataAttributeSyncVo.getBPrice().trim()));
        }
        // 含税供货价
        if (null != dataAttributeSyncVo.getGhPrice()) {
            goods.setSupplyTaxPrice(new BigDecimal(dataAttributeSyncVo.getGhPrice()));
        }
        // 商品卖点
        goods.setSellingPoint(dataAttributeSyncVo.getGoodsSelling());
        //商品名称
        goods.setGoodsName(dataAttributeSyncVo.getGoodsName());
        return goods;
    }


    /**
     * 货品数据属性
     *
     * @param dataAttributeSyncVo
     */
    private Inventory setInventoryData(Inventory inventory, GoodsDataAttributeSyncVo dataAttributeSyncVo) {
        // 货品类型
        Integer firstChannel = dataAttributeSyncVo.getFirstChannel();
        if (null != inventory && null != inventory.getId()) {
            // 更新时间
            inventory.setUpdatedTime(LocalDateTime.now());
            // 更新人
            inventory.setUpdatedByName(UPDATE_BY_NAME);
        } else {
            // 创建时间
            inventory.setCreatedTime(LocalDateTime.now());
            // 库存编码
            inventory.setInventoryCode(dataAttributeSyncVo.getCode());
        }
        // 是否二奢
        if (FIRST_CHANNEL.equals(firstChannel)) {
            inventory.setIsSecondhand(YesOrNoEnum.NO.getCode());
        } else {
            inventory.setIsSecondhand(YesOrNoEnum.YES.getCode());
        }
        // 成色
        inventory.setQuality(dataAttributeSyncVo.getColour());
        // 成色值
        inventory.setQualityValue(dataAttributeSyncVo.getQualityValue());
        // 货品名称  取自商品名称
        inventory.setInventoryName(dataAttributeSyncVo.getGoodsName());
        // 货品成本对应胖总管的采购价
        if (null != dataAttributeSyncVo.getCgPrice()) {
            inventory.setInventoryCost(new BigDecimal(dataAttributeSyncVo.getCgPrice()));
        }
        // 入库价对应胖总管的入库价
        if(StringUtils.isNotBlank(dataAttributeSyncVo.getWPrice().trim())){
            inventory.setWarehousePrice(new BigDecimal(dataAttributeSyncVo.getWPrice().trim()));
        }
        // 主图
        inventory.setMainImage(dataAttributeSyncVo.getGoodsImages());
        // 商品详情图
        inventory.setDetailImage(dataAttributeSyncVo.getImgSrc());
        // 是否已中检
        /*if(StringUtils.isNotBlank(dataAttributeSyncVo.getTraceCode())){
            inventory.setIsDoneCcic(YesOrNoEnum.YES.getCode());
        }else{
            inventory.setIsDoneCcic(YesOrNoEnum.NO.getCode());
        }*/
        // 是否可中检
        if(dataAttributeSyncVo.getIsGuojian() == null || dataAttributeSyncVo.getIsGuojian().equals(0)){
            inventory.setIsUseCcic(YesOrNoEnum.NO.getCode());
        }else if(dataAttributeSyncVo.getIsGuojian().equals(1)){
            inventory.setIsUseCcic(YesOrNoEnum.YES.getCode());
        }
        // 货品类型（主品，附件，配件，赠品）
        inventory.setInventoryType(1);
        return inventory;
    }

    /**
     * 保存商品数据同步日志
     *
     * @Method saveGoodsSyncLog
     * @Author lcx
     * @CreatedDate 2021/7/1 10:04
     * @Throws Exception
     */
    private void saveGoodsSyncLog(String code, int status, String content,Integer type) {
        //生成相应日志
        try {
            PhGoodsSyncLogs PhGoodsSyncLogs = new PhGoodsSyncLogs();
            PhGoodsSyncLogs.setInventoryCode(code);
            PhGoodsSyncLogs.setType(String.valueOf(type));
            PhGoodsSyncLogs.setStatus(status);
            PhGoodsSyncLogs.setContent(content);
            PhGoodsSyncLogs.setCreatedTime(new Date());
            phGoodsSyncLogsService.save(PhGoodsSyncLogs);
        } catch (Exception e) {
            log.error("新增商品数据同步日志表异常:{}", e.getMessage());
        }
    }

    /**
     * 保存关系表数据
     *
     * @param goods
     * @param inventory
     * @param dataAttributeSyncVo
     */
    public void saveMdData(Goods goods, Inventory inventory, GoodsDataAttributeSyncVo dataAttributeSyncVo) {
        // 创建中间表信息
        GoodsInventoryMd inventoryMd = new GoodsInventoryMd();
        inventoryMd.setGoodsId(goods.getId());
        inventoryMd.setInventoryId(inventory.getId());
        boolean mdRow = goodsInventoryMdService.save(inventoryMd);
        if (mdRow) {
//            saveGoodsSyncLog(inventory.getInventoryCode(), CONSTANTINTONE, "新增货品与商品属性参数:" + JSON.toJSON(dataAttributeSyncVo).toString());
            log.info("商品中心属性数据，新增货品与商品关系数据成功...");
        }
    }

    /**
     * 校验商品编码是否已存在
     *
     * @return
     */
    public boolean checkIsExistGoodsCode(String goodsCode) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("goods_code", goodsCode);
        int count = goodsService.count(wrapper);
        return count > 0;
    }
}